# app/api/v1/system/user_management.py
import logging
from typing import Optional, List

from fastapi import APIRouter, Body, Query, Path
from tortoise.expressions import Q

from app.controllers.base.user import user_controller,role_controller
from app.controllers.family.family_system import family_controller
from app.schemas.base.user import *

from app.utils.request import RequestHandler
from app.utils.app_log import logger
from app.schemas.base.login import CredentialsSchema, JWTOut, JWTPayload
from app.core.auth import get_current_user_required,get_current_superuser
from fastapi import APIRouter, Depends, Query

router = APIRouter()

# ==================== 用户管理 ====================
@router.get("/user/list", summary="获取用户列表")
async def get_users(
    page: int = Query(1, description="页码"),
    page_size: int = Query(10, description="每页数量"),
    username: Optional[str] = Query(None, description="用户名称，用于搜索"),
    email: Optional[str] = Query(None, description="邮箱地址"),
    family_id: Optional[int] = Query(None, description="家庭ID"),
    current_user: JWTPayload = Depends(get_current_superuser)   ## 限制管理员使用
):
    """获取用户列表"""
    q = Q()
    if username:
        q &= Q(username__contains=username)
    if email:
        q &= Q(email__contains=email)
    if family_id is not None:
        q &= Q(family_id = family_id)

    total,data = await user_controller.user_list(page=page, page_size=page_size, q=q)
    return RequestHandler.success_paginated(data=data, total=total, page=page, page_size=page_size)


@router.get("/user/{user_id}", summary="获取用户详情")
async def get_user(
    user_id: int = Path(..., description="用户ID"),
):
    """获取用户详情"""
    user_info = await user_controller.get_user_info(user_id)
    return RequestHandler.success(data=user_info)
    

@router.delete("/user/{user_id}", summary="删除用户")
async def delete_user(
    user_id: int = Path(..., description="用户ID"),
    current_user: JWTPayload = Depends(get_current_superuser)   ## 限制管理员使用
):
    """删除用户"""

    delete = await user_controller.remove_user(user_id=user_id)
    if delete:
        return RequestHandler.success(message="用户删除成功")
    

@router.post("/user/{user_id}/reset-password", summary="重置密码")
async def reset_password(
    user_id: int = Path(..., description="用户ID"),
    current_user: JWTPayload = Depends(get_current_user_required)  # 添加认证依赖,需登录的用户
):
    """重置用户密码"""
    reset_password = await user_controller.reset_password(user_id)
    if reset_password:
        return RequestHandler.success(message="密码已重置为123456")

@router.post("/user/create", summary="创建用户")  ## 不能限制。
async def create_user(
    user_in: UserCreate,
):
    """创建用户"""
    logger.info(f"创建用户: {user_in.username}")
    user = await user_controller.create_user(user_in)
    if user:
        return RequestHandler.success(message="用户创建成功")
    
@router.put("/user/{user_id}", summary="更新用户")
async def update_user(
    user_id: int = Path(..., description="用户ID"),
    user_in: UserUpdate = None,
    current_user: JWTPayload = Depends(get_current_user_required)  # 添加认证依赖,需登录的用户
):
    """更新用户"""
    if user_in:
        user_in.id = user_id
    user = await user_controller.update_user_info(user_id, user_in)
    if user:
        return RequestHandler.success(message="用户更新成功")
    
## 用户部分 经过修改 可以使用 ###




# ==================== 角色管理 ====================

@router.get("/roles/list", summary="查看角色列表")
async def list_roles(
    page: int = Query(1, description="页码"),
    page_size: int = Query(10, description="每页数量"),
    role_name: str = Query("", description="角色名称，用于查询"),
):
    """获取角色列表"""
    try:
        q = Q()
        if role_name:
            q = Q(name__contains=role_name)
        total, role_objs = await role_controller.list(page=page, page_size=page_size, search=q)
        data = [await obj.to_dict() for obj in role_objs]
        return RequestHandler.success_paginated(data=data, total=total, page=page, page_size=page_size)
    except Exception as e:
        logger.error(f"获取角色列表失败: {str(e)}")
        return RequestHandler.server_error(message="获取角色列表失败")

@router.get("/roles/{role_id}", summary="查看角色详情")
async def get_role(
    role_id: int = Path(..., description="角色ID"),
):
    """获取角色详情"""
    try:
        role_obj = await role_controller.get(id=role_id)
        return RequestHandler.success(data=await role_obj.to_dict())
    except Exception as e:
        logger.error(f"获取角色详情失败: {str(e)}")
        return RequestHandler.server_error(message="获取角色详情失败")

@router.post("/roles/create", summary="创建角色")
async def create_role(role_in: RoleCreate):
    """创建角色"""
    try:
        if await role_controller.is_exist(name=role_in.name):
            return RequestHandler.error(code=400, message="该角色名称已存在")
        
        await role_controller.create(obj_in=role_in)
        return RequestHandler.success(message="角色创建成功")
    except Exception as e:
        logger.error(f"创建角色失败: {str(e)}")
        return RequestHandler.server_error(message="创建角色失败")

@router.put("/roles/{role_id}", summary="更新角色")
async def update_role(
    role_id: int = Path(..., description="角色ID"),
    role_in: RoleUpdate = None,
):
    """更新角色"""
    try:
        role_in.id = role_id
        await role_controller.update(id=role_id, obj_in=role_in)
        return RequestHandler.success(message="角色更新成功")
    except Exception as e:
        logger.error(f"更新角色失败: {str(e)}")
        return RequestHandler.server_error(message="更新角色失败")

@router.delete("/roles/{role_id}", summary="删除角色")
async def delete_role(
    role_id: int = Path(..., description="角色ID"),
):
    """删除角色"""
    try:
        await role_controller.remove(id=role_id)
        return RequestHandler.success(message="角色删除成功")
    except Exception as e:
        logger.error(f"删除角色失败: {str(e)}")
        return RequestHandler.server_error(message="删除角色失败")

@router.get("/roles/{role_id}/permissions", summary="查看角色权限")
async def get_role_permissions(
    role_id: int = Path(..., description="角色ID")
):
    """获取角色权限"""
    try:
        role_obj = await role_controller.get(id=role_id)
        data = await role_obj.to_dict(m2m=True)
        return RequestHandler.success(data=data)
    except Exception as e:
        logger.error(f"获取角色权限失败: {str(e)}")
        return RequestHandler.server_error(message="获取角色权限失败")

@router.post("/roles/{role_id}/permissions", summary="更新角色权限")
async def update_role_permissions(
    role_id: int = Path(..., description="角色ID"),
    permission_data: RoleUpdateMenusApis = None,
):
    """更新角色权限"""
    try:
        role_obj = await role_controller.get(id=role_id)
        await role_controller.update_roles(
            role=role_obj, 
            menu_ids=permission_data.menu_ids, 
            api_infos=permission_data.api_infos
        )
        return RequestHandler.success(message="角色权限更新成功")
    except Exception as e:
        logger.error(f"更新角色权限失败: {str(e)}")
        return RequestHandler.server_error(message="更新角色权限失败")

# ==================== 用户角色关联 ====================

@router.get("/user/{user_id}/roles", summary="获取用户角色")
async def get_user_roles(
    user_id: int = Path(..., description="用户ID"),
):
    """获取用户的所有角色"""
    try:
        user_obj = await user_controller.get(id=user_id)
        roles = await user_obj.roles.all()
        role_data = [await role.to_dict() for role in roles]
        return RequestHandler.success(data=role_data)
    except Exception as e:
        logger.error(f"获取用户角色失败: {str(e)}")
        return RequestHandler.server_error(message="获取用户角色失败")

@router.post("/user/{user_id}/roles/connect", summary="分配用户角色")
async def assign_user_roles(
    user_id: int = Path(..., description="用户ID"),
    role_ids: List[int] = Body(..., description="角色ID列表"),
):
    """为用户分配角色"""
    try:
        user_obj = await user_controller.get(id=user_id)
        await user_controller.update_roles(user_obj, role_ids)
        return RequestHandler.success(message="用户角色分配成功")
    except Exception as e:
        logger.error(f"分配用户角色失败: {str(e)}")
        return RequestHandler.server_error(message="分配用户角色失败")